import config
from api.request import session
from api.common import get_time
from api.login import login_token, get_auth_url, get_user
from utils.login_code import LoginCode

class Login:
    def __init__(self):
        self.code = LoginCode()
        self.token = None
        self.user = None

    def load(self):
        if config.read('token') is not None:
            self.set_token(config.read('token'))
    
    def get_qrcode_url(self):
        # 使用服务器时间戳 生成code
        code = self.code.build(get_time())
        # 生成认证url
        return get_auth_url(code)

    def check_login(self):
        # 要先生成 code
        if self.code.code == None:
            return False
        response = login_token(self.code.code)
        if response['err'] == 0:
            self.set_token(response['token'])
            return True
        elif response['err'] == 6245:
            return False
    
    def set_token(self, token):
        self.token = token
        # 保存 token
        config.write('token', token)
        # request 加入 token
        session.params.update({"key": token})
        # 更新用户信息
        self.get_user()

    def get_user(self):
        response = get_user()
        if response['err'] == 0:
            self.user = response['user_info']
        else:
            self.user = None

